/**
 * 
 */
package org.picWeb.view.service;

import static org.picWeb.util.ConfigKeys.MODEL;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import lombok.Setter;

import org.apache.commons.io.FileUtils;
import org.picWeb.entity.PicDetail;
import org.picWeb.entity.PicIndex;
import org.picWeb.util.ConfigKeys;
import org.springframework.ui.ModelMap;

/**
 * @author zjm
 * @version org.picWeb.view.service/PicIndexTblActionService.java 2011-6-24
 */

public class PicIndexTblActionService {

	@Setter
	private ObjectDaoInterface objectDao;

	public void addMdf(PicIndex picIndex, List<PicDetail> details) throws Exception {

		Set<PicDetail> set = new HashSet<PicDetail>();
		long count = 0;
		if (null != picIndex.getId()) {
			String hql = "select count(*) from PicDetail t where t.picIndex.id = '" + picIndex.getId() + "'";

			count = (Long) objectDao.findOne(hql);
		}
		
		if (null != details) {
			for (PicDetail detail : details) {
				detail.setPicIndex(picIndex);
				set.add(detail);
			}
			count += details.size();
		}
		
		picIndex.setPicCount((int) count);
		picIndex.setPicdetails(set);

		objectDao.addupdate(picIndex);

	}

	public void delete(PicIndex index) throws Exception {
		index = (PicIndex) objectDao.findOne(PicIndex.class, index.getId());
		String deleteSql = "delete from PicDetail where parentId = ?";

		objectDao.update(deleteSql, new String[] { index.getId() });
		objectDao.delete(index);

		int savePathLen = ConfigKeys.paramPath.split("/").length;
		String[] imgPath = index.getGroupPhoto().split("/");

		FileUtils.deleteDirectory(new File(ConfigKeys.savePath + imgPath[savePathLen]));

	}

	public void get(Class clazz, String id, ModelMap map) throws Exception {
		PicIndex index = (PicIndex) objectDao.findOne(clazz, id);

		map.put(MODEL, index);
	}

	public void deleteDetail(String id, String[] imgPaths) throws Exception {
		String img1 = null;
		String img2 = null;
		String img3 = null;

		if (null != id) {
			PicDetail detail = (PicDetail) objectDao.findOne(PicDetail.class, id);
			PicIndex index = detail.getPicIndex();

			if (index.getPicCount() != null)
				index.setPicCount(index.getPicCount() - 1);

			objectDao.delete(detail);
			objectDao.update(index);

			img1 = ConfigKeys.appPath + detail.getSmallPic();
			img2 = ConfigKeys.appPath + detail.getMiddlePic();
			img3 = ConfigKeys.appPath + detail.getOriginalPic();
		} else {
			img1 = ConfigKeys.appPath + imgPaths[2];
			img2 = ConfigKeys.appPath + imgPaths[1];
			img3 = ConfigKeys.appPath + imgPaths[0];
		}

		new File(img1).delete();
		new File(img2).delete();
		new File(img3).delete();

	}
}
